package com.library.common.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.lcodecore.tkrefreshlayout.IHeaderView
import com.lcodecore.tkrefreshlayout.OnAnimEndListener
import com.library.common.R
import java.text.SimpleDateFormat
import java.util.*

/**
 * Author：SimGa
 * CoryRight：2018/12/3
 * PackageName：com.simga.library.com.vitabuybuy.tv.widget
 */
class RefreshViewHolder @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), IHeaderView {
    private var mHeaderStatusTv: TextView? = null
    private var mHeaderHintTv: TextView? = null
    private val mPullDownRefreshText = "下拉刷新..."
    private val mReleaseRefreshText = "松手刷新..."
    private val mRefreshingText = "加载中..."
    private fun init() {
        val headView =
            View.inflate(context, R.layout.view_refresh_header, null)
        //        headView.setBackgroundColor(Color.parseColor("#f7f7f7"));
        mHeaderStatusTv = headView.findViewById(R.id.tv_normal_refresh_header_status)
        mHeaderHintTv = headView.findViewById(R.id.tv_time)
        mHeaderStatusTv?.text = mPullDownRefreshText
        mHeaderHintTv?.text = getNowTime("yyyy-MM-dd HH:mm")
        addView(headView)
        gravity = Gravity.CENTER
        //        setBackgroundColor(Color.parseColor("#f7f7f7"));
    }

    override fun getView(): View {
        return this
    }

    override fun onPullingDown(
        fraction: Float,
        maxHeadHeight: Float,
        headHeight: Float
    ) {
        if (fraction < 1f) mHeaderStatusTv!!.text = mPullDownRefreshText
        if (fraction > 1f) mHeaderStatusTv!!.text = mReleaseRefreshText
    }

    override fun onPullReleasing(
        fraction: Float,
        maxHeadHeight: Float,
        headHeight: Float
    ) {
        if (fraction < 1f) {
            mHeaderStatusTv!!.text = mPullDownRefreshText
        }
    }

    override fun startAnim(
        maxHeadHeight: Float,
        headHeight: Float
    ) {
        mHeaderStatusTv!!.text = mRefreshingText
    }

    override fun onFinish(listener: OnAnimEndListener) {
        listener.onAnimEnd()
    }

    override fun reset() {
        mHeaderStatusTv!!.text = mPullDownRefreshText
    }

    companion object {
        @SuppressLint("SimpleDateFormat")
        fun getNowTime(style: String?): String {
            val nowDate = Date()
            val now = Calendar.getInstance()
            now.time = nowDate
            val formatter = SimpleDateFormat(style)
            return formatter.format(now.time)
        }
    }
    init {
        init()
    }
}